package uk.co.q3c.deplan.client.service;

import java.util.List;

import uk.co.q3c.deplan.client.Orchestrator;
import uk.co.q3c.deplan.client.domain.dag.DAG;
import uk.co.q3c.deplan.client.domain.resource.PersistenceReferenceException;
import uk.co.q3c.deplan.client.domain.task.Task;
import uk.co.q3c.deplan.client.domain.task.Task;
import uk.co.q3c.deplan.server.service.TaskService_BigT;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.googlecode.objectify.Key;

/**
 * All access to task objects from persistence should be through this class. It checks the cache first, then if the required objects are not
 * found, then they are returned to the call back method via an RPC call. In some cases this class does nothing but route a call to the RPC
 * layer, as the callback method itself is responsible for ensuring the cache is refreshed with any newly retrieved objects. there is a lot
 * of similarity between this and the server side implementation {@link TaskService_BigT} of the {@link TaskService} interface, but not
 * enough to use the same interface.
 * 
 * @author David Sowerby 4 Jul 2010
 * 
 */
public class TaskServiceClient {

	private final Key<DAG<Key<? extends Task>>> dependenciesKey;
	private DAG<Key<? extends Task>> dependencies;
	private TaskServiceAsync rpc;

	public TaskServiceClient() {
		dependenciesKey = new Key<DAG<Key<? extends Task>>>(null, (Class<? extends DAG<Key<? extends Task>>>) DAG.class, new Long(1));
	}

	public void closeSession() {
		throw new RuntimeException("Not yet implemented");

	}

	public void countPlanManagers(AsyncCallback<Integer> callback) {
		rpc.countPlanManagers(callback);

	}

	public void setRpc(TaskServiceAsync rpc) {
		this.rpc = rpc;
	}

	public void predecessorsFor(Task task, AsyncCallback<List<? extends Task>> callback) throws PersistenceReferenceException {
		DAG<Key<? extends Task>> dependencies = getDependencies();
		dependencies.getPredecessors(task.getKey());
	}

	public void save(Task task) {

	}

	public DAG<Key<? extends Task>> getDependencies() {
		DAG<Key<? extends Task>> dependencies = Orchestrator.getCache()
				.get(dependenciesKey);
		if (dependencies == null) {
			throw new RuntimeException("not yet implemented");
		} else {
			return dependencies;
		}
	}

	public void setDependencies(DAG<Key<? extends Task>> dependencies) {
		this.dependencies = dependencies;
	}

}
